// 导入数据库操作模块
const { mysql } = require("../../db");
const moment = require("moment");
const { filesURL } = require("../../../config");

// 获取所有路由
// exports.Info = (req, res) => {
//     const sqlStr1 = `SELECT * FROM anime where is_delete = 0`;
//     const sqlStr2 =
//         `
//         SELECT a.*, 
//             (
//                 SELECT JSON_ARRAYAGG(t.name)
//                 FROM anime_types AS at
//                 JOIN types AS t ON at.type_id = t.id
//                 WHERE at.anime_id = a.id
//             ) AS types,
//             au.name AS authorship,
//             d.name AS director,
//             (
//                 SELECT JSON_ARRAYAGG(
//                         JSON_OBJECT(
//                             'voice_actor', va.name,
//                             'name', r.name,
//                             'nickname', r.nickname,
//                             'avatar', r.avatar,
//                             'gender', r.gender,
//                             'intro', r.intro
//                         )
//                 )
//                 FROM anime_voice_roles AS avr
//                 JOIN voice_roles AS vr ON avr.voice_roles_id = vr.id
//                 JOIN voice_actor AS va ON vr.voice_id = va.id
//                 JOIN roles AS r ON vr.roles_id = r.id
//                 WHERE avr.anime_id = a.id
//             ) AS content
//         FROM anime AS a
//         JOIN anime_authorship AS aa ON a.id = aa.anime_id
//         JOIN authorship AS au ON aa.authorship_id = au.id
//         JOIN anime_director AS ad ON a.id = ad.anime_id
//         JOIN director AS d ON ad.director_id = d.id
//         WHERE a.is_delete = 0
//         GROUP BY a.id, au.name, d.name
//         LIMIT 0, 1000          
//         `;

//     mysql.query(sqlStr1, (err, results1) => {
//         if (err) return res.cc(err)
//         if (results1.length === 0) return res.cc("暂无番剧信息!");

//         mysql.query(sqlStr2, (err, results2) => {
//             if (err) return res.cc(err);

//             // 剔除results1中和results2中id相同项并保留results2的
//             const idSet = new Set(results2.map(item => item.id));
//             const resultsDict = {};
//             for (const item of results2) {
//                 resultsDict[item.id] = item;
//             }

//             const results = results1.filter(item => !idSet.has(item.id)).concat(Object.values(resultsDict));

//             const data = results.map(o => ({
//                 ...o,
//                 cover: o.cover ? `${filesURL}/images/cover/${o.cover}` : null,
//                 nickname: '《' + o.nickname + '》',
//                 animename: '『' + o.animename + '』',
//                 country:
//                     o.country === 0 ? '国内' :
//                         o.country === 1 ? '日本' :
//                             o.country === 2 ? '欧美' : '未知',
//                 premiere: moment(o.premiere).format('YYYY年MM月DD日'),
//                 create: moment(o.create).format('YYYY-MM-DD HH:mm:ss'),
//                 content: o.content ? o.content.map(c => ({
//                     ...c,
//                     avatar: c.avatar ? `${filesURL}/images/roles/${c.avatar}` : null
//                 })) : []
//             }));

//             res.json({
//                 status: 0,
//                 message: "获取番剧信息成功!",
//                 data
//             })
//         })
//     })
// }

const formatData = (results) => {
	try {
		const data = results.map(o => ({
			...o,
			cover: o.cover ? `${filesURL}/images/cover/${o.cover}` : null,
			c_name: "《" + o.c_name + "》",
			animename: "『" + o.animename + "』",
			country: ["国内", "日本", "欧美"][o.country] || "其他",
			premiere: moment(o.premiere).format("YYYY年MM月DD日"),
			create: moment(o.create).format("YYYY-MM-DD HH:mm:ss"),
			content: o.content ? o.content.map(c => ({
				...c,
				avatar: c.avatar ? `${filesURL}/images/roles/${c.avatar}` : null
			})) : []
		}));
		return data;
	} catch (err) {
		throw err;
	}
};

exports.Info = async (req, res, table) => {
	try {
		const sqlStr = `SELECT * FROM ${table} WHERE is_delete = 0`;
		const [results] = await mysql.query(sqlStr);
		if (results.length === 0) return res.error("获取失败，无番剧信息！");
		const data = formatData(results);
		return res.success(data);
	} catch (err) {
		return res.error(err);
	}
};

// 添加番剧
exports.Add = async (req, res, table) => {
	const { animename, c_name, country, intro, episodes, premiere, update, op, ed } = req.body;
	const info = [animename, c_name, country, intro, episodes, premiere, update, op, ed];
	try {
		const sqlStr = `INSERT INTO ${table} SET ?`;
		const [results] = await mysql.query(sqlStr, info);
		if (results.affectedRows !== 1) return res.error("新增失败");
		return res.success("新增成功");
	} catch (err) {
		return res.error(err);
	}
};

// 修改番剧
exports.Update = async (req, res, table) => {
	const { animename, c_name, country, intro, op, ed, premiere, updated, id } = req.body;
	const info = [animename, c_name, country, intro, op, ed, premiere, updated, id];
	try {
		const sqlStr = `UPDATE ${table} SET animename=?,c_name=?,country=?,intro=?,op=?,ed=?,premiere=?,updated=? WHERE id=?`;
		const [results] = await mysql.query(sqlStr, info);
		if (results.affectedRows !== 1) return res.error("修改失败");
		return res.success("修改成功");
	} catch (err) {
		return res.error(err);
	}
};

exports.Search = async (req, res, table) => {
	const info = req.params.value;

	try {
		const sqlStr = `SELECT * From ${table} WHERE (animename LIKE ? OR c_name LIKE ? OR intro LIKE ? OR country LIKE ? OR rate LIKE ?) AND is_delete = 0`;
		const SeletePattern = `%${info}%`;
		const values = Array(5).fill(SeletePattern);
		const [results] = await mysql.query(sqlStr, values);
		if (results.length === 0) return res.error("该番剧不存在！");
		const data = formatData(results);
		return res.success(data);
	} catch (err) {
		return res.error(err);
	}
};